#!/usr/bin/perl

##HACKABOT_HELP##
# Some stats on the current channel.
# !stats
##HACKABOT_HELP##

use strict;
use DBI;
use Time::localtime;
use XML::Simple;

my $CONFIG = XMLin($ENV{'HACKABOT_CFG'}, 
	ForceArray => ['privatechan'],
	KeyAttr => { privatechan => "+chan" });
my $CMDCFG = $CONFIG->{'cmdconfig'}->{'seen'};
my $DBCFG = $CONFIG->{'cmdconfig'}->{'database'};

my $dbhost = $DBCFG->{'host'};
my $dbname = $DBCFG->{'name'};
my $dbuser = $DBCFG->{'user'};
my $dbpass = $DBCFG->{'pass'};


my ($chan, $msg);
while (<>) {
	if (/^to\s*(#\S*)/) {
		$chan = $1;
	}
	elsif (/^msg\s*(#\S*)/) {
		$msg = $1;
	}
}

if (defined $msg) {
	$chan = $msg;
}

if (defined $chan) {
	my ($dbh, $sth);
	my $row;
	my ($max, $max_date);
	

	$dbh = DBI->connect("DBI:mysql:$dbname:$dbhost", $dbuser, $dbpass, { PrintError => 1 });
	if (!$dbh) {
		die "see: Failed to connect to database\n";
	}

	my $chanq = $dbh->quote($chan);
	
	$sth = $dbh->prepare("SELECT num, date FROM log WHERE chan = $chanq AND type = 'stats' ORDER BY num DESC, id DESC LIMIT 1");
	$sth->execute();
	if ($row = $sth->fetchrow_hashref) {
		$max = $row->{'num'};
		$max_date = $row->{'date'}
	}
	else {
		die "stats: missing stats db entry\n";
	}
	$sth->finish();

	$dbh->disconnect;

	print "send $chan max nicks: $max $max_date\n"
}
